// src/pages/home/widgets/updateUserChannel/widgets/selected/index.tsx
import styles from "@pages/home/widgets/channel/styles/edit.module.less";
import classNames from "classnames";
import GeekIcon from "@shared/geekIcon";
import React, { useEffect, useState } from "react";
import { useDeleteUserChannelMutation, useRequestUserChannelsQuery } from "@service/channel";
import toast from "react-hot-toast";
import { SlideRef } from "@shared/slide";
import { useNavigate, useParams } from "react-router-dom";
import EditButton from "@pages/home/widgets/common/EditButton";
interface Props {
  slideRef: React.RefObject<SlideRef | null>;
}

export default function Selected({ slideRef }: Props) {
  // 获取路由参数
  const { cid }  = useParams();
  // 获取用于实现页面跳转的方法
  const navigate = useNavigate();
  // 获取用户频道列表
  // 如果本地缓存存在数据则直接从本地缓存中获取, 本地缓存中没有则和服务端进行同步
  const { selectedChannels } = useRequestUserChannelsQuery(undefined, {
    selectFromResult: ({ data }) => ({ selectedChannels: data?.data.channels }),
  });
  // 用于控制频道是否处于可删除状态
  const [editing, setEditing] = useState(false);
  // 用于删除用户频道
  const [deleteUserChannel, { isSuccess }] = useDeleteUserChannelMutation();

  // 检测频道是否删除成功
  useEffect(() => {
    // 频道删除成功 给出用户提示
    if (isSuccess) toast.success("频道删除成功");
  }, [isSuccess]);

  // 检测频道数量是否剩余4个
  useEffect(() => {
    // 如果频道数量剩余4个, 取消编辑状态
    if (selectedChannels?.length === 4) setEditing(false);
  }, [selectedChannels]);
  // 如果没有数据
  if (typeof selectedChannels === "undefined") return null;
  return (
    <>
      <div className={styles.title}>
        <h3>我的频道</h3>
        <h4>点击进入频道</h4>
        <EditButton value={editing} onChange={setEditing} render={selectedChannels.length > 4} />
      </div>
      <div className={styles.list}>
        {selectedChannels.map((channel) => (
          <span key={channel.id} className={classNames({ [styles.active]: channel.id === Number(cid) })}  onClick={() => {
            navigate(`/${channel.id}`);
            slideRef.current?.close();
          }}>
            {channel.name}
            {/* 如果处于编辑状态并且当前频道不是"推荐" 渲染删除按钮 */}
            {editing && channel.id !== 0 && (
              <GeekIcon
                type={"iconbtn_tag_close"}
                onClick={(event) =>{ deleteUserChannel(channel.id); event.stopPropagation();if (channel.id===Number(cid)) {
                  navigate(`/0`);
                }}}
              />
            )}
          </span>
        ))}
      </div>
    </>
  );
}